<template>
  <view class="chart-wrapper">
    <canvas canvas-id="trendChart" id="trendChart" class="chart"></canvas>
  </view>
</template>

<script setup>
import { onMounted, watch } from 'vue'
import * as echarts from '@/static/echarts.min' // 需要将echarts.min.js放在static目录

const props = defineProps({
  chartData: {
    type: Object,
    required: true
  }
})

let chart = null

onMounted(() => {
  initChart()
})

watch(() => props.chartData, () => {
  if (chart) {
    updateChart()
  }
}, { deep: true })

const initChart = () => {
  const canvas = uni.createCanvasContext('trendChart', this)
  chart = echarts.init(canvas, null, {
    width: uni.upx2px(690),
    height: uni.upx2px(500)
  })
  canvas.clear()
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: props.chartData.legend,
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.chartData.xAxis
    },
    yAxis: {
      type: 'value'
    },
    series: props.chartData.series.map(item => ({
      ...item,
      type: 'line',
      smooth: true,
      lineStyle: {
        width: 3
      }
    }))
  }
  
  chart.setOption(option)
  canvas.draw()
}

const updateChart = () => {
  const option = {
    legend: {
      data: props.chartData.legend
    },
    xAxis: {
      data: props.chartData.xAxis
    },
    series: props.chartData.series.map(item => ({
      ...item,
      data: item.data
    }))
  }
  
  chart.setOption(option)
}
</script>

<style scoped>
.chart-wrapper {
  width: 100%;
  height: 100%;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>